use std::cell::RefCell;
use std::rc::Rc;

// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

// impl TreeNode {
//     #[inline]
//     pub fn new(val: i32) -> Self {
//         TreeNode {
//             val,
//             left: None,
//             right: None
//         }
//     }
//
// }



/*

struct TreeAncestor {
    ancestors: Vec<Vec<i32>>,
}


/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl TreeAncestor {

    fn new(n: i32, parent: Vec<i32>) -> Self {
        let mut ancestors = vec![vec![-1;16];n as usize];
        for i in 0..n as usize {
            ancestors[i][0] = parent[i];
        }
        for j in 1..16 {
            for i in 0..n as usize {
                if ancestors[i][j-1] != -1 {
                    ancestors[i][j] = ancestors[ancestors[i][j-1] as usize][j-1];
                }
            }
        }

        Self {
            ancestors,
        }
    }

    // fn get_kth_ancestor(&self, node: i32, k: i32) -> i32
    // 要mut
    fn get_kth_ancestor(&self, mut node: i32, k: i32) -> i32 {
        for j in 0..16 {
            if ((k >> j) & 1) != 0 {
                node = self.ancestors[node as usize][j];

                if node == -1 {
                    return -1;
                }
            }
        }

        node

    }
}

/**
 * Your TreeAncestor object will be instantiated and called as such:
 * let obj = TreeAncestor::new(n, parent);
 * let ret_1: i32 = obj.get_kth_ancestor(node, k);
 */




// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None
        }
    }
}

use std::rc::Rc;
use std::cell::RefCell;

*/